import React, { useState } from "react";

import "./index.css";

import { message } from "antd";

import service from "@/http/request";

import { useNavigate } from "react-router-dom";

import { useDispatch } from "react-redux";
import { setUserName, setRole } from "@/store/userSlice";

import { setHasLuckyFrame } from "@/store/userSlice"; 

function Login({ onStep }) {
  const dispatch = useDispatch();

  let [username, setUsername] = useState("");
  let [password, setPassword] = useState("");

  let update = (type, newVal) => {
    if (type == "username") setUsername(newVal);
    if (type == "password") setPassword(newVal);
  };

  const navigate = useNavigate();

  const login = async () => {
    console.log(111);
    if (!username) {
      message.error("用户名不能为空");
      return;
    }
    if (!password) {
      message.error("密码不能为空");
      return;
    }

    try {
      const data = await service.post("/users/login", {
        username,
        password,
      });
      dispatch(setUserName(username));
      dispatch(setRole(data.role));
      dispatch(setHasLuckyFrame(data.hasLuckyFrame))

      localStorage.setItem("token", data.token);
      localStorage.setItem("role", data.role);
      navigate("/");
      message.success("登录成功");
    } catch (error) {
      message.error("登录失败");
    }
  };

  const register = () => {
    navigate("/user/register");
  };

  return (
    <div className="login-form">
      <div className="homepage-form-title">用户登录</div>
      <div className="underline"></div>
      <div className="login-form-label">
        <span>账号</span>
        <span>*</span>
      </div>
      <input
        placeholder="请输入账号"
        value={username}
        type="text"
        onInput={(e) => update("username", e.currentTarget.value)}
      />
      <div className="login-form-label">
        <span>密码</span>
        <span>*</span>
      </div>
      <input
        placeholder="请输入密码"
        value={password}
        type="password"
        onInput={(e) => update("password", e.currentTarget.value)}
      />
      <div>
        <button type="submit" className="submit-button" onClick={login}>
          登录
        </button>
        <button
          type="register"
          className="to-register-button"
          onClick={register}
        >
          注册
        </button>
      </div>
    </div>
  );
}

export default Login;
